package com.eco.common.swagger;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.OAuthBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.*;


/**
 * @author Administrator
 */
@Configuration
@EnableSwagger2WebMvc
@Import(BeanValidatorPluginsConfiguration.class)
@Slf4j
public class SwaggerAutoConfiguration{

    @Bean
    @ConditionalOnMissingBean
    public SwaggerProperties swaggerProperties() {
        return new SwaggerProperties();
    }


//    @Override
//    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
//        this.beanFactory = beanFactory;
//    }
//
//    @Bean
//    public List<Docket> createRestApi() {
//        ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;
//        List<Docket> docketList = new LinkedList<>();
//
//        //schema
//        List<GrantType> grantTypes = new ArrayList<>();
//        //密码模式
//        String passwordTokenUrl = swaggerProperties().getPasswordTokenUrl();
//        ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant = new ResourceOwnerPasswordCredentialsGrant(passwordTokenUrl);
//        grantTypes.add(resourceOwnerPasswordCredentialsGrant);
//        OAuth oAuth = new OAuthBuilder().name("oauth2")
//                .grantTypes(grantTypes).build();
//        //context
//        //scope方位
//        List<AuthorizationScope> scopes = new ArrayList<>();
//        scopes.add(new AuthorizationScope("read", "read  resources"));
//        scopes.add(new AuthorizationScope("write", "write resources"));
//        scopes.add(new AuthorizationScope("reads", "read all resources"));
//        scopes.add(new AuthorizationScope("writes", "write all resources"));
//
//        SecurityReference securityReference = new SecurityReference("oauth2", scopes.toArray(new AuthorizationScope[]{}));
//        SecurityContext securityContext = new SecurityContext(Lists.newArrayList(securityReference), PathSelectors.ant("/**"));
//        //schemas
//        List<SecurityScheme> securitySchemes = Lists.newArrayList(oAuth);
//        //securyContext
//        List<SecurityContext> securityContexts = Lists.newArrayList(securityContext);
//
//        Docket docket = new Docket(DocumentationType.SWAGGER_2)
//                .enable(swaggerProperties().getEnabled() == null?false:swaggerProperties().getEnabled())
//                .select()
//                .apis(RequestHandlerSelectors.basePackage(swaggerProperties().getBasePackage()))
//                .paths(PathSelectors.any())
//                .build()
//                .securityContexts(securityContexts)
//                .securitySchemes(securitySchemes)
//                .apiInfo(apiInfo());
//
//        configurableBeanFactory.registerSingleton("defaultDocket", docket);
//
//        docketList.add(docket);
//
//        return docketList;
//    }
@Bean
public Docket restApi() {
    //schema
    List<GrantType> grantTypes = new ArrayList<>();
    //密码模式
    ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant = new ResourceOwnerPasswordCredentialsGrant(swaggerProperties().getPasswordTokenUrl());
    grantTypes.add(resourceOwnerPasswordCredentialsGrant);
    //context
    //scope方位
    List<AuthorizationScope> scopes = new ArrayList<>();
    scopes.add(new AuthorizationScope("read", "read  resources"));
    scopes.add(new AuthorizationScope("write", "write resources"));
    scopes.add(new AuthorizationScope("reads", "read all resources"));
    scopes.add(new AuthorizationScope("writes", "write all resources"));
    OAuth oAuth = new OAuthBuilder().name("oauth2").scopes(scopes)
            .grantTypes(grantTypes).build();
    SecurityReference securityReference = new SecurityReference("oauth2", scopes.toArray(new AuthorizationScope[]{}));
    SecurityContext securityContext = new SecurityContext(Collections.singletonList(securityReference), PathSelectors.ant("/**"));
    //schemas
    List<SecurityScheme> securitySchemes = Lists.newArrayList(oAuth);
    //securyContext
    List<SecurityContext> securityContexts = Lists.newArrayList(securityContext);
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            // .apis(RequestHandlerSelectors.basePackage("com.youlai.admin.controller"))
            // .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
            .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
            .paths(PathSelectors.any())
            .build()
            .securityContexts(securityContexts)
            .securitySchemes(securitySchemes)
            .apiInfo(apiInfo());
}

//    private List<SecurityReference> defaultAuth() {
//        AuthorizationScope authorizationScope = new AuthorizationScope("web", "access_token");
//        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
//        authorizationScopes[0] = authorizationScope;
//        return Collections.singletonList(new SecurityReference("Bearer",authorizationScopes));
//    }

    private ApiKey apiKey() {
        return new ApiKey("Bearer", "Authorization", "header");
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("系统管理")
                .description("<div style='font-size:14px;color:red;'>用户、角色、部门、菜单、权限、字典、客户端接口</div>")
                .termsOfServiceUrl("https://www.youlai.tech")
                .contact(new Contact("有来技术团队", "https://gitee.com/youlaiorg", "youlaitech@163.com"))
                .license("Open Source")
                .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0")
                .version("1.0.0")
                .build();
    }

}
